<template>
  <div class="o-m2o-editor">
    <o-m2o-selector
      :disabled="disabled"
      v-model="config.toTable"
      :placeholder="$srv.getI18nByPath('vxe.m2o.toTable')"
      @on-dochange="onTableSelected"
      :filter="filter"
      tTable="_sys_fun"
      tField="title"
    ></o-m2o-selector>
    <div class="m2o-set-part" v-if="isSetM2o !== null && isSetM2o === true">
      <div
        class="m2o-set-item"
        v-show="
          $srv.getx(config, 'toTable', true, v => {
            if (v && !$srv.utils.has(config, 'isFunLayout')) {
              config.isFunLayout = true;
            }
          })
        "
      >
        <span>{{ $srv.getI18nByValue('是否全功能展示') }}：</span>
        <vxe-switch
          v-model="config.isFunLayout"
          :disabled="!config.toTable || disabled"
          size="small"
          open-label="全"
          close-label="单"
          @change="m2oCfChange"
          class="m2o-set-switch-one"
        ></vxe-switch>
      </div>
    </div>
    <!-- <Poptip
      trigger="click"
      :title="$srv.getI18nByPath('vxe.m2o.det')"
      :transfer="true"
      :disabled="config.toTable === ''"
      @on-popper-show="onPopperShow"
      @on-popper-hide="onPopperHide"
    >
      <Button size="small" shape="circle" icon="ios-settings"></Button>
      <div class="m2o-editor-detail" slot="content">
        <Checkbox v-model="config.isDropdown" @on-change="emitChange">{{
          $srv.getI18nByPath('vxe.m2o.selMode')
        }}</Checkbox>
        <i-input
          :placeholder="$srv.getI18nByPath('vxe.m2o.storage')"
          v-model="config.customSearch"
          @on-blur="emitChange"
          style="width: 140px; margin: 10px 10px; 10px 20px"
        ></i-input>
        <i-input
          :placeholder="$srv.getI18nByPath('vxe.m2o.glue')"
          v-model="config.multiConnect"
          @on-blur="emitChange"
          style="width: 140px; margin: 10px 20px 10px 10px"
        ></i-input>
        <Table
          :columns="tableColumns"
          :data="tableData"
          height="300"
          width="436"
        >
          <template slot-scope="{ index }" slot="isShow">
            <Checkbox
              v-model="tableData[index].isShow"
              @on-change="emitChange"
            ></Checkbox>
          </template>
          <template slot-scope="{ index }" slot="filter">
            <i-input
              v-model="tableData[index].filter"
              @on-blur="emitChange"
            ></i-input>
          </template>
          <template slot-scope="{ index }" slot="sort">
            <i-input
              v-model="tableData[index].sort"
              @on-blur="emitChange"
            ></i-input>
          </template>
          <template slot-scope="{ index }" slot="isReturn">
            <Checkbox
              v-model="tableData[index].isReturn"
              @on-change="emitChange"
            ></Checkbox>
          </template>
        </Table>
      </div>
    </Poptip> -->
  </div>
</template>
<script lang="ts">
import { ifs, T_srv, Tsrv, vue } from '@/services';

@T_srv.comp
export default class oM2oEditor extends vue {
  @T_srv.prop({ required: false, default: false }) disabled: boolean;

  @T_srv.prop({ required: false, default: null }) isSetM2o: boolean;

  @T_srv.prop({ required: false, default: {} }) filter: ifs.I_filter;

  // modify by wiz
  public compName: string = 'oM2oEditor';

  /**
   * props
   */
  private config = {
    toTable: '',
    toField: '',
    isDropdown: false,
    customSearch: '',
    multiConnect: '',
    isFunLayout: true, // true 全功能， false 单个
    fields: []
  };

  private tableColumns = [
    {
      title: Tsrv.getI18nByPath('vxe.m2o.title'),
      key: 'title',
      width: '100',
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('vxe.m2o.isShow'),
      key: 'isShow',
      slot: 'isShow',
      width: '60',
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('vxe.m2o.filter'),
      key: 'filter',
      width: '100',
      slot: 'filter',
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('vxe.m2o.sort'),
      key: 'sort',
      width: '100',
      slot: 'sort',
      align: 'center'
    },
    {
      title: Tsrv.getI18nByPath('vxe.m2o.isReturn'),
      key: 'isReturn',
      width: '60',
      slot: 'isReturn',
      align: 'center'
    }
  ];

  private tableData = [
    // {
    //   title: "",
    //   isShow: false,
    //   filter: "",
    //   key: ""
    // }
  ];

  @T_srv.model('model-change') value: any;

  @T_srv.watch('value', { deep: true })
  onValueChange(val: any) {
    this.init(val);
  }

  created() {
    this.init(this.value);
  }

  mounted() {}

  private onTableSelected(e: any) {
    if (e !== null) {
      this.config.toTable = e['title'];
      this.config.toField = e['desc_field'];
      this.config.fields = [];
      this.tableData = [];
    } else {
      this.config.toTable = '';
      this.config.toField = '';
      this.config.fields = [];
      this.tableData = [];
    }
    this.emitChange();
  }

  private loadTableData(tableName: string) {
    //
    // 2.0废弃  报表改用积木报表 无此表_sys_querysqlplan
    // Tsrv.httpReqV1
    //   .query({
    //     fields: '_sys_fun_field.title',
    //     sqlBody: `from _sys_fun_field where _sys_fun_field._sys_fun_id = (select _sys_fun.id from _sys_fun where _sys_fun.title = '${tableName}')`
    //   })
    //   .then((res: any) => {
    //     let data: any = res.data;
    //     if (data.success) {
    //       if (data.rows.length === 0) {
    //         Tsrv.httpReqV1
    //           .query({
    //             fields: 'distinct t3.FFieldName,t3.FFieldCaption',
    //             sqlBody: `from _sys_querysql t1 inner join _sys_querysqlplan t2 on t1.id=t2.FSQLID and t2.FTypeID=0 inner join _sys_querysqlFilter t3 on t2.id=t3.FPlanID where t1._sys_fun_id=(select _sys_fun.id from _sys_fun where _sys_fun.title = '${tableName}')`
    //           })
    //           .then((res2: any) => {
    //             data = res2.data;
    //             if (data.success) {
    //               this.tableData = [];
    //               data.rows.forEach(el => {
    //                 this.tableData.push({
    //                   title: el.FFieldName,
    //                   isShow: true,
    //                   isReturn: false,
    //                   filter: '',
    //                   sort: ''
    //                 });
    //               });
    //             }
    //           });
    //       } else {
    //         this.tableData = [];
    //         data.rows.forEach(el => {
    //           this.tableData.push({
    //             title: el.title,
    //             isShow: true,
    //             isReturn: false,
    //             filter: '',
    //             sort: ''
    //           });
    //         });
    //       }
    //     }
    //   });
  }

  private onPopperShow() {
    if (
      this.config.fields &&
      this.config.fields.length === 0 &&
      this.config.toTable !== ''
    ) {
      this.loadTableData(this.config.toTable);
    }
  }

  private onPopperHide() {
    let flag = true;
    if (this.tableData) {
      for (let i = 0; i < this.tableData.length; i++) {
        if (
          this.tableData[i].isShow === false ||
          this.tableData[i].filter !== '' ||
          this.tableData[i].sort !== '' ||
          this.tableData[i].isReturn === true
        ) {
          flag = false;
          break;
        }
      }
    }

    if (flag === true) this.tableData = [];
    this.emitChange();
  }

  private init(obj: any) {
    if (obj) {
      if (typeof obj === 'string') {
        // 适配老json
        if (obj.indexOf(':') > -1) {
          const split = obj.split(':');
          this.config.toTable = split[0];
          this.config.toField = split[1];
          this.$emit('model-change', this.config);
          this.$emit('on-change', this.config);
        }
      } else {
        this.config = Tsrv.utils.clone(obj, true);
        this.config.isDropdown = !!this.config.isDropdown;
        this.tableData = this.config.fields;
      }
    } else {
      this.config.toTable = '';
      this.config.toField = '';
      this.config.isDropdown = false;
      this.config.customSearch = '';
      this.config.multiConnect = '';
      this.config.fields = [];
      this.config.isFunLayout = true;
      this.$emit('model-change', this.config);
      this.$emit('on-change', this.config);
    }
  }

  private emitChange() {
    if (Tsrv.utils.noValue(this.config.toField)) {
      this.$msg('-547,FE,90'); // "MTO没有指定描述字段",
      this.cleanConfig();
    }

    this.config.fields = this.tableData;
    this.$emit('model-change', this.config);
    this.$emit('on-change', this.config);
  }

  private cleanConfig() {
    // this.config.customSearch = null;
    // this.config.fields = [];
    // this.config.multiConnect = null;
    // this.config.toField = null;
    // this.config.toTable = null;
    this.config.customSearch = '';
    this.config.fields = [];
    this.config.multiConnect = '';
    this.config.toField = '';
    this.config.toTable = '';
  }

  private m2oCfChange() {
    this.emitChange();
  }
}
</script>

<style lang="scss" scoped>
.o-m2o-editor {
  display: flex;
  // flex-direction: row;
  // align-items: center;
  flex-direction: column;
  .o-m2o-selector {
    flex: 1;
  }
  .ivu-poptip {
    margin-left: 10px;
    flex-shrink: 0;
  }
  .m2o-set-part {
    display: flex;
    flex-direction: column;
    // .m2o-set-item {
    // .m2o-set-switch-one.vxe-switch .vxe-switch--button {
    //   background-color: #ffffff90;
    // }
    // }
  }
}
</style>
